#include "stdafx.h"
#include "stream/FileStream.hpp"
#include "charset/unicodeconverter.hpp"
using JHCPP::charset::CUnicodeConverter;
#include "filesys/file.hpp"
using JHCPP::filesys::CFile;
#include "stdlib/bugcheck.hpp"
using namespace JHCPP::stdlib;

STREAM_NAMESPACE_BEGIN

#ifdef JH_OS_WINDOWS

CFileStreamBuf::CFileStreamBuf()
	: BufferedBidirectionalStreamBuf(BUFFER_SIZE, std::ios::in | std::ios::out),
	m_handle(INVALID_HANDLE_VALUE),
	m_pos(0)
{
}

CFileStreamBuf::~CFileStreamBuf()
{
	close();
}

void CFileStreamBuf::open(const std::string& path, std::ios::openmode mode)
{
	jh_assert (m_handle == INVALID_HANDLE_VALUE);

	m_path = path;
	m_pos = 0;
	setMode(mode);
	resetBuffers();

	DWORD access = 0;
	if (mode & std::ios::in)
		access |= GENERIC_READ;
	if (mode & std::ios::out)
		access |= GENERIC_WRITE;

	DWORD shareMode = FILE_SHARE_READ;
	if (!(mode & std::ios::out))
		shareMode |= FILE_SHARE_WRITE;

	DWORD creationDisp = OPEN_EXISTING;
	if (mode & std::ios::trunc)
		creationDisp = CREATE_ALWAYS;
	else if (mode & std::ios::out)
		creationDisp = OPEN_ALWAYS;

	DWORD flags = FILE_ATTRIBUTE_NORMAL;

#ifdef _UNICODE
	std::wstring utf16Path;
	CUnicodeConverter::toUTF16(path, utf16Path);
	m_handle = CreateFileW(utf16Path.c_str(), access, shareMode, NULL, creationDisp, flags, NULL);
#else
	m_handle = CreateFileA(path.c_str(), access, shareMode, NULL, creationDisp, flags, NULL);
#endif

	if (m_handle == INVALID_HANDLE_VALUE)
		CFile::handleLastError(m_path);

	if ((mode & std::ios::ate) || (mode & std::ios::app))
		seekoff(0, std::ios::end, mode);
}

int CFileStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
	if (INVALID_HANDLE_VALUE == m_handle || !(getMode() & std::ios::in))
		return -1;

	if (getMode() & std::ios::out)
		sync();

	DWORD bytesRead(0);
	BOOL rc = ReadFile(m_handle, buffer, static_cast<DWORD>(length), &bytesRead, NULL);
	if (rc == 0)
		CFile::handleLastError(m_path);

	m_pos += bytesRead;

	return static_cast<int>(bytesRead);
}

int CFileStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
	if (INVALID_HANDLE_VALUE == m_handle || !(getMode() & std::ios::out))
		return -1;

	if (getMode() & std::ios::app)
	{
		LARGE_INTEGER li;
		li.QuadPart = 0;
		li.LowPart  = SetFilePointer(m_handle, li.LowPart, &li.HighPart, FILE_END);
		if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR)
			CFile::handleLastError(m_path);
		m_pos = li.QuadPart;
	}

	DWORD bytesWritten(0);
	BOOL rc = WriteFile(m_handle, buffer, static_cast<DWORD>(length), &bytesWritten, NULL);
	if (rc == 0)
		CFile::handleLastError(m_path);

	m_pos += bytesWritten;

	return static_cast<int>(bytesWritten);
}

bool CFileStreamBuf::close()
{
	bool success = true;
	if (m_handle != INVALID_HANDLE_VALUE)
	{
		try
		{
			if (getMode() & std::ios::out)
				sync();
		}
		catch (...)
		{
			success = false;
		}
		CloseHandle(m_handle);
		m_handle = INVALID_HANDLE_VALUE;
	}
	return success;
}

std::streampos CFileStreamBuf::seekoff(std::streamoff off, std::ios::seekdir dir, std::ios::openmode mode)
{
	if (INVALID_HANDLE_VALUE == m_handle || !(getMode() & mode))
		return -1;

	if (getMode() & std::ios::out)
		sync();

	std::streamoff adj;
	if (mode & std::ios::in)
		adj = static_cast<std::streamoff>(egptr() - gptr());
	else
		adj = 0;

	resetBuffers();

	DWORD offset = FILE_BEGIN;
	if (dir == std::ios::cur)
	{
		offset = FILE_CURRENT;
		off -= adj;
	}
	else if (dir == std::ios::end)
	{
		offset = FILE_END;
	}

	LARGE_INTEGER li;
	li.QuadPart = off;
	li.LowPart  = SetFilePointer(m_handle, li.LowPart, &li.HighPart, offset);

	if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR)
		CFile::handleLastError(m_path);
	m_pos = li.QuadPart;
	return std::streampos(static_cast<std::streamoff>(m_pos));
}

std::streampos CFileStreamBuf::seekpos(std::streampos pos, std::ios::openmode mode)
{
	if (INVALID_HANDLE_VALUE == m_handle || !(getMode() & mode))
		return -1;

	if (getMode() & std::ios::out)
		sync();

	resetBuffers();

	LARGE_INTEGER li;
	li.QuadPart = pos;
	li.LowPart  = SetFilePointer(m_handle, li.LowPart, &li.HighPart, FILE_BEGIN);

	if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR)
		CFile::handleLastError(m_path);
	m_pos = li.QuadPart;
	return std::streampos(static_cast<std::streamoff>(m_pos));
}

#elif defined JH_OS_LINUX

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

CFileStreamBuf::CFileStreamBuf()
	: BufferedBidirectionalStreamBuf(BUFFER_SIZE, std::ios::in | std::ios::out),
	m_fd(-1),
	m_pos(0)
{
}

CFileStreamBuf::~CFileStreamBuf()
{
	close();
}

void CFileStreamBuf::open(const std::string& path, std::ios::openmode mode)
{
	jh_assert (_fd == -1);

	m_pos = 0;
	m_path = path;
	setMode(mode);
	resetBuffers();

	int flags(0);
	if (mode & std::ios::trunc)
		flags |= O_TRUNC;
	if (mode & std::ios::app)
		flags |= O_APPEND;
	if (mode & std::ios::out)
		flags |= O_CREAT;
	if ((mode & std::ios::in) && (mode & std::ios::out))
		flags |= O_RDWR;
	else if (mode & std::ios::in)
		flags |= O_RDONLY;
	else
		flags |= O_WRONLY;

	m_fd = ::open(path.c_str(), flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
	if (m_fd == -1)
		CFile::handleLastError(m_path);

	if ((mode & std::ios::app) || (mode & std::ios::ate))
		seekoff(0, std::ios::end, mode);
}

int CFileStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
	if (m_fd == -1) return -1;

	if (getMode() & std::ios::out)
		sync();

	int n = read(m_fd, buffer, length);
	if (n == -1)
		CFile::handleLastError(m_path);
	m_pos += n;
	return n;
}

int CFileStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
	if (m_fd == -1) return -1;

	int n = write(m_fd, buffer, length);
	if (n == -1)
		CFile::handleLastError(m_path);
	m_pos += n;
	return n;
}

bool CFileStreamBuf::close()
{
	bool success = true;
	if (m_fd != -1)
	{
		try
		{
			sync();
		}
		catch (...)
		{
			success = false;
		}
		::close(m_fd);
		m_fd = -1;
	}
	return success;
}

std::streampos CFileStreamBuf::seekoff(std::streamoff off, std::ios::seekdir dir, std::ios::openmode mode)
{
	if (m_fd == -1 || !(getMode() & mode)) 
		return -1;

	if (getMode() & std::ios::out)
		sync();

	std::streamoff adj;
	if (mode & std::ios::in)
		adj = static_cast<std::streamoff>(egptr() - gptr());
	else
		adj = 0;

	resetBuffers();

	int whence = SEEK_SET;
	if (dir == std::ios::cur)
	{
		whence = SEEK_CUR;
		off -= adj;
	}
	else if (dir == std::ios::end)
	{
		whence = SEEK_END;
	}
	m_pos = lseek(m_fd, off, whence);
	return m_pos;
}

std::streampos CFileStreamBuf::seekpos(std::streampos pos, std::ios::openmode mode)
{
	if (m_fd == -1 || !(getMode() & mode)) 
		return -1;

	if (getMode() & std::ios::out)
		sync();

	resetBuffers();

	m_pos = lseek(m_fd, pos, SEEK_SET);
	return m_pos;
}

#endif


CFileIOS::CFileIOS(std::ios::openmode defaultMode) : m_defaultMode(defaultMode)
{
	
}

CFileIOS::~CFileIOS()
{
}

void CFileIOS::open(const std::string& path, std::ios::openmode mode)
{
	clear();
	m_buf.open(path, mode | m_defaultMode);
}

void CFileIOS::close()
{
	if (!m_buf.close())
	{
		setstate(ios_base::badbit);
	}
}

CFileStreamBuf* CFileIOS::rdbuf()
{
	return &m_buf;
}


CFileInputStream::CFileInputStream()
	: CFileIOS(std::ios::in),
	std::istream(&m_buf)
{
}

CFileInputStream::CFileInputStream(const std::string& path, std::ios::openmode mode)
	: CFileIOS(std::ios::in),
	std::istream(&m_buf)
{
	open(path, mode);
}

CFileInputStream::~CFileInputStream()
{
}


CFileOutputStream::CFileOutputStream()
	: CFileIOS(std::ios::out),
	std::ostream(&m_buf)
{
}

CFileOutputStream::CFileOutputStream(const std::string& path, std::ios::openmode mode)
	: CFileIOS(std::ios::out),
	std::ostream(&m_buf)
{
	open(path, mode);
}

CFileOutputStream::~CFileOutputStream()
{
}


CFileStream::CFileStream()
	: CFileIOS(std::ios::in | std::ios::out),
	std::iostream(&m_buf)
{
}

CFileStream::CFileStream(const std::string& path, std::ios::openmode mode)
	: CFileIOS(std::ios::in | std::ios::out),
	std::iostream(&m_buf)
{
	open(path, mode);
}

CFileStream::~CFileStream()
{
}

STREAM_NAMESPACE_END
